<template>
  <div class="overflow-hidden bg-white">
    <BasicTree
      ref="treeRef"
      title="部门列表"
      toolbar
      search
      treeWrapperClassName="h-[calc(100%-35px)] overflow-auto"
      :clickRowToExpand="false"
      :treeData="treeData"
      :defaultExpandAll="true"
      :fieldNames="{ key: 'id', title: 'name' }"
      @select="handleSelect"
    />
  </div>
</template>
<script lang="ts" setup>
  import { onMounted, ref, unref } from 'vue';
  import { BasicTree, TreeItem } from '@/components/Tree';
  import { deptTreeSelectApi } from '@/api/system/user';

  const emit = defineEmits(['select']);
  const treeRef = ref();
  function getTree() {
    const tree = unref(treeRef);
    if (!tree) {
      throw new Error('tree is null!');
    }
    return tree;
  }
  const treeData = ref<TreeItem[]>([]);

  async function fetch() {
    treeData.value = (await deptTreeSelectApi()) as unknown as TreeItem[];
    function deleteDisabled(data) {
      data.forEach((v) => {
        if (v.disabled) {
          v.name += '(已禁用)';
        }
        delete v.disabled;
        if (v.children) {
          deleteDisabled(v.children);
        }
      });
    }
    deleteDisabled(treeData.value);

    setTimeout(() => {
      // console.log(getTree());
      getTree().expandAll(true);
    }, 0);
  }

  function handleSelect(keys) {
    emit('select', keys[0]);
  }

  onMounted(() => {
    fetch();
  });
</script>
